package date;
/*数组实现栈*/
import java.util.Arrays;

public class MyStack<T> {
    private Object[] stack;
    private int size = 0;

    public MyStack() {
        stack = new Object[10];
    }

    //扩容
    public void expandCapacity(int size) {
        if (size > stack.length) {
            size = size >> 1;//扩容为原来的一半
            stack = Arrays.copyOf(stack, size);
        }

    }

    //判断是否为空
    public boolean isEmpty() {
        if (size == 0) {
            return true;
        }
        return false;
    }

    //入栈
    public void push(T t) {
        expandCapacity(size + 1);
        stack[size] = t;
        size++;
    }

    //出栈
    public T pop() {
        T t = peek();
        if (!isEmpty()) {
            stack[size - 1] = t;
        }
        size--;
        return t;

    }

    //栈顶元素
    public T peek() {
        T t = null;
        if (!isEmpty()) {
            t = (T) stack[size - 1];
        }
        return t;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < size; i++) {
            sb.append(stack[i] + ",");
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append("]");
        return sb.toString();
    }
}